<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\Area;
use think\facade\View;
use think\exception\ValidateException;
use app\common\model\Address as AddressModel;
use think\response\Json;

class Address extends Base
{

    public function index()
    {
        $map = ['uid' => $this->user->id];
        $list = AddressModel::getList($map, false, 'create_time', ['p', 'c', 'd']);
        View::assign('list', $list);
        $tpl = $this->request->param('type') ? 'choice' : 'index';
        return View::fetch($tpl);
    }

    public function add()
    {
        return View::fetch();
    }

    public function edit($id)
    {
        View::assign('info', AddressModel::where('id', $id)->find());
        return View::fetch();
    }

    public function save(): Json
    {
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'Address');
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
        return json(AddressModel::add($param, $this->user));

    }

    public function delete(): Json
    {
        return json(AddressModel::edit($this->request->post('id'), $this->user));
    }

    public function getArea($id, $level = 0)
    {
        return Area::getArea($id ?: 100000, $level);
    }

    public function choice()
    {
        return json(AddressModel::choice($this->request->post('id'), $this->user));
    }

}

